package com.hsogoo.ultraman.container;

import java.util.Iterator;
import java.util.ServiceLoader;

import com.hsogoo.ultraman.exceptions.UltramanConfigException;

/**
 * Created by za-huangsaigang on 2018/9/20.
 */
public class ConfigContainer {

    private static volatile Container container;
    private static final Object lock = new Object();

    private static Container getContainer() {
        if (container == null) {
            synchronized (lock) {
                if (container == null) {
                    try {
                        //通过ServiceLoader的方式加载
                        ServiceLoader<Container> loader =ServiceLoader.load(Container.class);
                        Iterator<Container> iterator = loader.iterator();
                        if (!iterator.hasNext()) {
                            throw new IllegalStateException(String.format(
                                    "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
                                    Container.class.getName()));
                        }
                        container = iterator.next();
                    } catch (Throwable ex) {
                        UltramanConfigException exception = new UltramanConfigException("Unable to initialize configContainer!", ex);
                        throw exception;
                    }
                }
            }
        }
        return container;
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            return getContainer().getBean(clazz);
        } catch (Throwable ex) {
            throw new UltramanConfigException(String.format("Unable to load instance for type %s!", clazz.getName()), ex);
        }
    }

}
